# -*- coding:utf8 -*-
import json
import traceback
import os
import re
import typing
from scrapy import Request
from squirrel_core.commons.utils.tools import calc_str_md5, upload_file
from squirrel_core.frame.spider_makaka import MakakaSpider

file_path = os.environ.get("FILE_PATH", "/")


class xhrace_score(MakakaSpider):
    name = "xhrace_score"
    serialNumber = ""
    header = {
        "Host": "www.xhrace.com",
        "Accept": "application/json, text/plain, */*",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
    }

    def get_ext_requests_or_urls(self, data=None):
        if data and isinstance(data, str):
            data = json.loads(data)
        if data and isinstance(data, typing.MutableMapping):
            self.serialNumber = data.get("serialNumber", "")
            race_id = data.get("spider_config", {}).get("race_id", "")
            user_id = data.get("spider_config", {}).get("user_id", "")
            race_no = data.get("spider_config", {}).get("race_no", "")
            user_name = data.get("spider_config", {}).get("user_name", "")
            card_num = data.get("spider_config", {}).get("card_num", "")
            race_name = data.get("spider_config", {}).get("race_name", "").replace(" ", "")
            home_url = data.get("spider_config", {}).get("url", "")
            if not home_url and not card_num:
                self.logger.info("url和card_num必须存在")
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 203, "message": "url和card_num必须存在"})
                self.close_after_idle = True
                self.force_to_close_spider = True
            else:
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 100, "message": "任务启动成功"})
                event_id = "".join(re.findall(r"eventId=(.*?)(?:&|$)", home_url))
                url = f"https://www.xhrace.com/api/statistics/front/getEvent/{event_id}"
                yield Request(url=url, callback=self.parse, dont_filter=True, errback=self.err_parse, headers=self.header,
                              meta={"race_id": race_id, "user_id": user_id, "user_name": user_name,
                                    "race_name": race_name, "card_num": card_num, "race_no": race_no})

    def parse(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_name = response.meta.get("race_name", "")
        user_name = response.meta.get("user_name", "")
        card_num = response.meta.get("card_num", "")
        race_no = response.meta.get("race_no", "")
        try:
            self.logger.info(f"开始解析赛事信息:{response.url}")
            content = json.loads(response.text).get("data", {})
            event_id = content.get("id", "")
            rule = content.get("sreachRule", "")
            if "2025三峰越野赛" in race_name or "2025七星关·蝴蝶径越野赛" in race_name:
                url = f"https://www.xhrace.com/api/event-mgr/eventParticipantList/getCurrentProjectId?eventId={event_id}&keyword={race_no}"
                yield Request(url=url, callback=self.parse_group1, dont_filter=True,
                              errback=self.err_parse, headers=self.header,
                              meta={"race_id": race_id, "user_id": user_id, "user_name": user_name, "race_no": race_no,
                                    "race_name": race_name, "card_num": card_num, "event_id": event_id})
            else:
                url = f"https://www.xhrace.com/api/event-mgr/eventParticipantList/frontSearch?eventId={event_id}&keyword={card_num}&sreachRule={rule}"
                yield Request(url=url, callback=self.parse_group, dont_filter=True,
                              errback=self.err_parse, headers=self.header,
                              meta={"race_id": race_id, "user_id": user_id, "user_name": user_name,
                                    "race_name": race_name, "card_num": card_num})
        except Exception:
            self.logger.info(f"解析赛事信息时出错{response.url}：{traceback.format_exc()}")

    def parse_group(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_name = response.meta.get("race_name", "")
        user_name = response.meta.get("user_name", "")
        card_num = response.meta.get("card_num", "")
        try:
            self.logger.info(f"开始解groupId信息:{response.url}")
            content_list = json.loads(response.text).get("data", [])
            for content in content_list:
                r_no = "".join(content.get("bibNumbers", [])).strip()
                event_list = content.get("eventRanksList", [])
                group_name = content.get("projectName", "")
                for event in event_list:
                    group_id = event.get("id", "")
                    url = f"https://www.xhrace.com/api/statistics/front/getIndividualScoresByBibNumbers?eventRanksId={group_id}&bibNumbers={r_no}"
                    yield Request(url=url, callback=self.parse_base, dont_filter=True,
                                  errback=self.err_parse, headers=self.header,
                                  meta={"race_id": race_id, "user_id": user_id, "user_name": user_name, "r_no": r_no,
                                        "race_name": race_name, "card_num": card_num, "group_id": group_id, "group_name":group_name})
        except Exception:
            self.logger.info(f"解析groupId信息时出错{response.url}：{traceback.format_exc()}")

    def parse_group1(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_name = response.meta.get("race_name", "")
        user_name = response.meta.get("user_name", "")
        card_num = response.meta.get("card_num", "")
        race_no = response.meta.get("race_no", "")
        event_id = response.meta.get("event_id", "")
        try:
            self.logger.info(f"开始解groupId信息:{response.url}")
            content = json.loads(response.text).get("data", [])
            group_id = content.get("eventRankId", "")
            score_data = {"race_name": race_name, "itemName": "",
                          "name": user_name, "raceNo": race_no, "pace": "",
                          "distance": "", "shotScore": "", "score": ""}
            url = f"https://www.xhrace.com/api/statistics/front/getIndividualScoresById?bibNumber={race_no}&eventRanksId={group_id}"
            yield Request(url=url, callback=self.parse_score, dont_filter=True,
                          errback=self.err_parse, headers=self.header,
                          meta={"race_id": race_id, "user_id": user_id, "user_name": user_name,
                                "race_name": race_name, "card_num": card_num,
                                "score_data": score_data})
        except Exception:
            self.logger.info(f"解析groupId信息时出错{response.url}：{traceback.format_exc()}")

    def parse_base(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_name = response.meta.get("race_name", "")
        user_name = response.meta.get("user_name", "")
        card_num = response.meta.get("card_num", "")
        group_id = response.meta.get("group_id", "")
        r_no = response.meta.get("r_no", "")
        group_name = response.meta.get("group_name", "")
        try:
            self.logger.info(f"开始查找{user_name}基本成绩信息:{response.url}")
            data_list = json.loads(response.text).get("data", [])
            for data in data_list:
                score_data = {"race_name": race_name, "itemName": group_name,
                              "name": data.get("fillName", user_name), "raceNo": r_no, "pace": "",
                              "distance": f"{data.get('currentDistance', 0)}KM", "shotScore": "", "score": ""}

                url = f"https://www.xhrace.com/api/statistics/front/getIndividualScoresById?bibNumber={r_no}&eventRanksId={group_id}"
                yield Request(url=url, callback=self.parse_score, dont_filter=True,
                              errback=self.err_parse, headers=self.header,
                              meta={"race_id": race_id, "user_id": user_id, "user_name": user_name,
                                    "race_name": race_name, "card_num": card_num,
                                    "score_data": score_data})
        except Exception:
            self.logger.info(f"查找{user_name}基本成绩信息时出错{response.url}：{traceback.format_exc()}")

    def parse_score(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_name = response.meta.get("race_name", "")
        user_name = response.meta.get("user_name", "")
        card_num = response.meta.get("card_num", "")
        score_data = response.meta.get("score_data", {})
        try:
            self.logger.info(f"开始解析{user_name}的成绩:{response.url}")
            content = json.loads(response.text).get("data", {})
            score_data["pace"] = content.get("avgSpeed", "")
            score_data["distance"] = content.get("projectName", "")
            score_data["shotScore"] = self.get_score(content.get("eventScore", "")) if content.get("eventScore", "") else 0
            score_data["score"] = self.get_score(content.get("netScore", "")) if content.get("netScore", "") else 0
            score_info = []
            data_list = content.get("list", [])
            for data in data_list:
                cp_name = data.get("currentCheckpoint", "")
                start_time = data.get("checkInTime", "")
                stop_time = self.get_score(data.get("elapsedTime", "")) if data.get("elapsedTime", "") else 0
                cp_length = data.get("distanceFromStart", "")
                speed = ""
                score_info.append(
                    {"cp_name": cp_name, "start_time": start_time, "score": stop_time, "distance": cp_length,
                     "pace": speed})
            if score_info:
                score_info[-1]["cp_name"] = "FINISH"
            score_data["sectionScore"] = score_info
            score_data.update({"fastPace": "", "slowPace": "", "certImg": ""})
            project_id = content.get("projectId", "")
            if project_id:
                race_no = score_data.get('raceNo', '')
                url = f"https://www.xhrace.com/api/statistics/front/certInfoShow/{project_id}/{race_no}"
                yield Request(url=url, callback=self.parse_cert, errback=self.err_parse, dont_filter=True, headers=self.header,
                              meta={"race_id": race_id, "user_id": user_id, "score_data": score_data,
                                    "project_id": project_id, "race_no": race_no})
            else:
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str(score_data)}
                yield result
        except Exception:
            self.logger.info(f"查找{user_name}的成绩时出错{response.url}：{traceback.format_exc()}")

    def parse_cert(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        score_data = response.meta.get("score_data", {})
        project_id = response.meta.get("project_id", "")
        race_no = response.meta.get("race_no", "")
        try:
            self.logger.info(f"开始解析{race_no}的证书链接:{response.url}")
            cert_data = json.loads(response.text).get("data", [])
            if cert_data:
                cert_id = cert_data[0]
                cert_url = f"https://www.xhrace.com/api/statistics/front/certInfoImg/{project_id}/{race_no}/{cert_id}"
                yield Request(url=cert_url, callback=self.parse_pic, errback=self.err_parse, dont_filter=True,
                              meta={"race_id": race_id, "race_no": race_no, "user_id": user_id,
                                    "score_data": score_data, "download_timeout": 60})
            else:
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str(score_data)}
                yield result
        except Exception:
            self.logger.info(f"解析{race_no}的证书链接时出错{response.url}：{traceback.format_exc()}")

    def parse_pic(self, response):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_no = response.meta.get("race_no", "")
        score_data = response.meta.get("score_data", {})
        try:
            self.logger.info(f"开始下载{race_no}的证书：{response.url}")
            pic_md5 = calc_str_md5(response.url)
            pic_name = f"{race_no}_{pic_md5}.jpg"
            dir_path = os.path.join(file_path, "picture", self.name_first)
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)
            save_path = os.path.join(dir_path, pic_name)
            if not os.path.exists(save_path):
                with open(save_path, "wb") as f:
                    f.write(response.body)
                upload_path = f"flow/{race_id}/{user_id}/pic/{pic_name}"
                upload_flag = upload_file(save_path, upload_path)
                if upload_flag:
                    self.logger.info(f"{save_path}上传成功：{upload_path}")
                else:
                    self.logger.info(f"{save_path}上传失败：{upload_path}")
                score_data["certImg"] = upload_path
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str(score_data)}
                yield result
        except Exception:
            self.logger.info(f"下载{race_no}证书时出错{response.url}：{traceback.format_exc()}")

    def get_score(self, time_str):
        try:
            hour = str(int(time_str / 3600 / 1000)).zfill(2)
            minute = str(int(time_str / 1000 % 3600 / 60)).zfill(2)
            seconds = str(round(time_str / 1000.0 % 3600 % 60 + 0.5)).zfill(2)
            return f"{hour}:{minute}:{seconds}"
        except Exception:
            self.logger.info(f"处理赛事成绩时出错:{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")

